package net.maku.api.module.storage.util;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

public class HttpUtil {
    public static InputStream urlToInputStream(String path) {
        URL url = null;
        InputStream is =null;
        try {

            //将中文转成urlencode，将特殊字符转换回来，不然会请求异常，报错找不到资源
            String urlencoded =
                    URLEncoder.encode(path, "utf-8")
                            .replaceAll("%3A", ":")
                            .replaceAll("%2F", "/")
                            .replaceAll("%2C", ",")
                            .replaceAll("%7B", "{")
                            .replaceAll("%3F","?")
                            .replaceAll("%7D", "}");
            url = new URL(urlencoded);

        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();//利用HttpURLConnection对象,我们可以从网络中获取网页数据.
            conn.setDoInput(true);
            conn.connect();
            is = conn.getInputStream();	//得到网络返回的输入流

        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }
}
